/**
 *
 */
package com.zhuoyue.zhtj.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.eit.eitsite.common.utils.HttpUtils;
import com.eit.eitsite.common.utils.IdGen;
import com.google.common.collect.Lists;
import com.zhuoyue.elmt.utils.GsonUtils;
import com.zhuoyue.zhtj.common.Consts;
import com.zhuoyue.zhtj.dao.KckqjlDao;
import com.zhuoyue.zhtj.dao.KkcdtjDao;
import com.zhuoyue.zhtj.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.service.CrudService;
import com.zhuoyue.zhtj.dao.KqjlDao;

/**
 * 考勤记录Service
 *
 * @author hss
 * @version 2017-09-26
 */
@Service
@Transactional(readOnly = true)
public class KqjlService extends CrudService<KqjlDao, Kqjl> {
    @Autowired
    private KqjlDao kqjlDao;
    @Autowired
    private KckqjlDao kckqjlDao;
    @Autowired
    private KkcdtjDao kkcdtjDao;

    public Kqjl get(String id) {
        return super.get(id);
    }

    public List<Kqjl> findList(Kqjl kqjl) {
        return super.findList(kqjl);
    }

    public Page<Kqjl> findPage(Page<Kqjl> page, Kqjl kqjl) {
        return super.findPage(page, kqjl);
    }

    @Transactional(readOnly = false)
    public void save(Kqjl kqjl) {
        super.save(kqjl);
    }

    @Transactional(readOnly = false)
    public void delete(Kqjl kqjl) {
        super.delete(kqjl);
    }


    public List<Kqjl> getKqjlByNum(Kqjl kqjl) {
        List<Kqjl> list = kqjlDao.selectKqjlByNum(kqjl);
        if (list != null && list.size() > 0) {
            return list;
        }
        return null;
    }

    @Transactional(readOnly = false)
    public boolean getCourseBykqjl(Kqjl kqjl) {
        List<Kqjl> list = getKqjlByNum(kqjl);
        if (list != null) {
            if(handldKqjl(list)){
                return true;
            }
        }
        return false;
    }

    private Kckqjl assembleKckqjl(Kqjl kqjl, String[] dstr) {
        Kckqjl k = new Kckqjl();
        k.setNumber(kqjl.getNum());
        k.setSemeyear(getsemeterYearByDate(dstr[0]));
        k.setSemester(getSemeterByDate(dstr[0]));
        return k;
    }

    /**
     * 处理考勤记录
     *
     * @param lists
     * @return
     * @throws Exception
     */
    @Transactional(readOnly = false)
    private boolean handldKqjl(List<Kqjl> lists){
        try {
            for (Kqjl kqjl : lists) {
                String[] dstr = kqjl.getRdate().split(" ");
                String week = getWeekByDate(dstr[0]);//根据日期判定星期几
                int zc = getWeek(dstr[0]);//根据日期获取第几周
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String course = kckqjlDao.selectInfoByKckqjl(assembleKckqjl(kqjl, dstr));
                if (course != null) {
                    List<Course> weekOfCourse = Lists.newArrayList();
                    Course[] studentCourse = GsonUtils.newInstance().fromJson(course, Course[].class);
                    List<Course> list2=getCourseByZc(zc,studentCourse);//获取指定周课程
                    //获取指定周指定星期课程集合
                    for (Course courseItem : list2) {
                        if (courseItem.getXq().equals(week)) {
                            weekOfCourse.add(courseItem);
                        }
                    }
                    if (weekOfCourse.size() > 0) {
                        for (Course course1 : weekOfCourse) {
                            String[] sjd=getTimeByCoure(course1).split("-");
                            String sk = dstr[0] + " " + sjd[0];//上课时间
                            String xk=dstr[0] + " " + sjd[1];//下课时间
                            long time1 = sdf.parse(sk).getTime();//上课时间
                            long time2 = sdf.parse(xk).getTime();//下课时间
                            long time3 = time1 - Consts.BEFORETIME * 60 * 1000;
                            long time4 = time1 + Consts.LATETIME * 60 * 1000;
                            long time5 = time1 + Consts.LAPSETIME * 60 * 1000;
                            long times = sdf.parse(kqjl.getRdate()).getTime();
                            if(times>time3&&times<time2){
                                if(times>time1&&times<time4){
                                    Kkcdtj k=assembleKkcdtj(course1,kqjl);
                                    k.setState("1");//1代表迟到打卡
                                    k.setTime(kqjl.getRdate());
                                    if(kkcdtjDao.selectInfo(k)<=0){
                                        kkcdtjDao.insert(k);
                                    }
                                }
                                if(times>time4){
                                    Kkcdtj k=assembleKkcdtj(course1,kqjl);
                                    k.setState("2");//2代表旷课打卡
                                    k.setTime(kqjl.getRdate());
                                    if(kkcdtjDao.selectInfo(k)<=0){
                                        kkcdtjDao.insert(k);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private Kkcdtj assembleKkcdtj(Course course,Kqjl kqjl){
        Kkcdtj k=new Kkcdtj();
        k.setNum(kqjl.getNum());
        k.setTeacher(course.getJs());
        k.setKdz(course.getJsdz());
        k.setId(IdGen.uuid());
        k.setKname(course.getKcmc());
        return k;
    }

    private List<Course> getCourseByZc(int zc,Course[] all){
        List<Course> list=Lists.newArrayList();
        for (Course item:all){
            if(hasZcCourse(zc,item)){
                list.add(item);
            }
        }
        return list;
    }

    /**
     * 根据周次判定是否有课
     * @param course
     * @return
     */
    public boolean hasZcCourse(int zcs,Course course){
        String zcTem = course.getZc().replace("周", "");
        //形如3-16,19-20
        if (zcTem.indexOf("，") != -1) {
            zcTem = zcTem.replace("，", ",");
        }
        if(zcTem.indexOf(",")!=-1){
            String[] str1=zcTem.split(",");
            for(String item:str1){
                String[] str2=item.split("-");
                if(zcs>=Integer.parseInt(str2[0])&&zcs<=Integer.parseInt(str2[1])){
                    return true;
                }
            }
        }
        //形如3-16
        if(zcTem.indexOf("-")!=-1){
            String[] str2=zcTem.split("-");
            if(zcs>=Integer.parseInt(str2[0])&&zcs<=Integer.parseInt(str2[1])){
                return true;
            }else {
                return false;
            }
        }
        //形如17
        if(Integer.parseInt(zcTem)==zcs){
            return true;
        }
        return false;
    }

    /**
     * 根据日期判定周次
     *
     * @param nowDate
     * @return
     */
    private int getWeek(String nowDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            long time = sdf.parse(nowDate).getTime() - sdf.parse(Consts.startSchool).getTime();
            return (int) (time / 1000 / 3600 / 24 / 7);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private TCourse assembleTCourse(Course course1, Kqjl kqjl) {
        TCourse tCourse = new TCourse();
        tCourse.setCourse(course1);
        tCourse.setNum(kqjl.getNum());
        return tCourse;
    }

    private String getTimeByCoure(Course course) {
        String[] jcs = course.getJc().replace("节", "").replace("，", ",").split(",");
        StringBuffer sb = new StringBuffer();
        for (String item : jcs) {
            sb.append(item);
        }
        String jc = sb.toString();
        if (jc.equals("12")) {
            return Consts.TIMECOURSEONE;
        } else if(jc.equals("123")) {
            return Consts.TIMECOURSESEVEN;
        }else if (jc.equals("234")) {
            return Consts.TIMECOURSETWO;
        } else if (jc.equals("34")) {
            return Consts.TIMECOURSETHREE;
        } else if (jc.equals("56") ) {
            return Consts.TIMECOURSEFOUR;
        } else if(jc.equals("567")){
          return Consts.TIMECOURSEEIGHT;
        } else if (jc.equals("78") || jc.equals("77+")) {
            return Consts.TIMECOURSEFIVE;
        } else if (jc.equals("89")) {
            return Consts.TIMECOURSESIX;
        }
        return null;
    }


    private String getsemeterYearByDate(String date) {
        String[] tdate = date.split("-");
        String year = "";
        if (tdate != null) {
            //根据月份判定学年
            if (Integer.parseInt(tdate[1]) > Consts.YEARMONTH) {
                year = tdate[0] + (Integer.parseInt(tdate[0]) + 1);
            } else {
                year = (Integer.parseInt(tdate[0]) - 1) + tdate[0];
            }
        }
        return year;
    }

    private String getSemeterByDate(String date) {
        String[] tdate = date.split("-");
        String semeter = "";
        if (tdate != null) {
            //根据月份判定学年
            if (Integer.parseInt(tdate[1]) > Consts.SEMETERMONTH) {
                semeter = "1";
            } else {
                semeter = "2";
            }
        }
        return semeter;
    }

    /**
     * 根据日期获取星期
     *
     * @param date
     * @return
     */
    private String getWeekByDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] week = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return week[w];
    }
}